var express = require("express");
var router = express.Router();
const jwt = require("jsonwebtoken");
var multiparty = require("multiparty");
var path = require("path");
var { usersModel, face, } = require("../module/model");
const { randomCode, sendCode } = require("./utils/getMessage");
const tencentcloud = require('tencentcloud-sdk-nodejs-iai')


// 短信验证码
router.post('/getCode', async (req, res) => {
	let code = randomCode(4);
	console.log(code);

	let phone = parseInt(req.query.phone);
	console.log(phone);
	sendCode(phone, code, (err, data) => {
		if (!err) {
			console.log(err);
			res.send({ code: 500, msg: "验证码发送失败" });
		} else {
			res.send({ code, msg: "验证码发送成功" });
		}
	});
})

//短信验证码登录
router.post("/phonelogin", async (req, res) => {
	let { phone } = req.body;
	try {
		let info = await usersSchema.findOne({ rel: phone });
		if (info) {
			const accessToken = jwt.sign({ rel: rel }, "abcdefg", {
				expiresIn: "3s",
			});
			const refreshToken = jwt.sign({ rel: rel }, "abcdefg", {
				expiresIn: "10s",
			});
			res.send({
				code: 200,
				userid: info._id,
				msg: "登录成功",
				accessToken,
				refreshToken
			});
		} else {
			res.send({
				code: 201,
				msg: "登录失败",
			});
		}
	} catch (error) {
		res.send({ message: "短信登录失败", error: error.message });
	}
});

//账号密码登录
router.post("/login", async (req, res) => {
	let rel = req.body.rel;
	let pass = req.body.password;
	console.log(rel, pass);
	const data = await usersModel.find({ rel: rel, password: pass })
	if (data) {
		console.log(123);
		const accessToken = jwt.sign({ rel: rel }, "abcdefg", {
			expiresIn: "1s",
		});
		const refreshToken = jwt.sign({ rel: rel }, "abcdefg", {
			expiresIn: "3s",
		});
		res.send({ code: 200, msg: "登录成功", accessToken, refreshToken, data });
	} else {
		res.send({ code: 400, msg: "登录失败" });
	}
});
//注册账号密码
router.get("/ljydeng", async (req, res) => {
	let user = req.query.username;
	let pass = req.query.password;
	let data = [
		{
			username: user,
			password: pass,
			phone: user, //手机号
			name: "用户" + Math.random(150), //用户昵称
			img: "https://img1.baidu.com/it/u=534429813,2995452219&fm=253&fmt=auto?w=800&h=800",
			vip: 0,
			vipTime: "", //图片地址
			registerTime: new Date().getTime(), //注册时间
		},
	];
	await usersSchema.create(data);
	res.send({ code: 200, msg: "注册成功" });
});
router.get("/jjjs", async (req, res) => {
	let data = await face.find();
	res.send(data);
});
//刷新token
router.get("/refresh", (req, res) => {
	console.log("333333333333333");
	const token = req.body.token;
	let rel = "";
	try {
		const userInfo = jwt.verify(token, "abcdefg");
		rel = userInfo.rel;
	} catch (error) {
		return res.status(401).json({
			code: 20000,
			msg: "token 失效，请重新登录",
		});
	}
	const userInfo = {
		rel,
	};
	const accessToken = jwt.sign(userInfo, "abcdefg", {
		expiresIn: "1s",
	});
	const refreshToken = jwt.sign(userInfo, "abcdefg", {
		expiresIn: "3s",
	});
	res.json({
		code: 10000,
		data: {
			accessToken,
			refreshToken,
		},
	});
});

//人脸登录
router.post('/facelogin', async (req, res) => {
	const { b64 } = req.body
	const IaiClient = tencentcloud.iai.v20200303.Client
	const clientConfig = {
		credential: {
			secretId: 'AKID88xkU4RcfV8XjjX8XlmZ9VeZGk14uWv8', //自己的secretId
			secretKey: '5xd5KNFuLZaNwJSO8g071iBXigQxHOHC'//密钥
		},


		region: 'ap-beijing', //地域参数  (华北地区/北京)
		profile: {
			httpProfile: {
				endpoint: 'iai.tencentcloudapi.com'
			}
		}
	}
	const client = new IaiClient(clientConfig)

	const params = {
		'GroupIds': [
			'ybk12276533'//创建的人员库（项目id）
		],
		'Image': b64, // 上传的图片为前端传递来的图片
		'NeedPersonInfo': 1,//当认证成功后，是否返回该人员的信息!  默认为0,（0不返回，1返回）
		'QualityControl': 0,//图片质量控制。0为不进行控制，1为较低的质量要求
		'FaceMatchThreshold': 85,//对比度大于85才可以认证成功，否则不成功
	};
	try {
		let doc = await client.SearchFaces(params)
		console.log(doc.Results[0].Candidates[0]);

		if (doc.Results[0].Candidates.length != 0) {
			let personName = doc.Results[0].Candidates[0].PersonName
			let data = await usersModel.find({ username: personName })
			if (data) {
				const accessToken = jwt.sign({ rel: data[0].rel }, "abcdefg", {
					expiresIn: "3s",
				});
				const refreshToken = jwt.sign({ rel: data[0].rel }, "abcdefg", {
					expiresIn: "10s",
				});
				res.send({
					code: 200,
					AccessToken: accessToken,
					RefreshToken: refreshToken,
					data,
				})
			}

		} else {
			res.send({
				code: 404,

			})
		}
	} catch (error) {
		res.send({
			code: 500,
			error: '服务器内部错误'
		})
	}

})



module.exports = router;